//
//  YBKeychainUtils.m

//
//  Created by edy on 2022/3/3.
//

#import "YBKeychainUtils.h"
#import "UICKeyChainStore.h"

@interface YBKeychainUtils ()

@property (nonatomic, strong) UICKeyChainStore *keyChain;

@end


@implementation YBKeychainUtils

+ (void)load {
    [self sharedKeyChain];
}

static NSString *_deviceUniqueId;

+ (NSString *)deviceId {
    if (nil == _deviceUniqueId) {// 双锁
        _deviceUniqueId = [YBKeychainUtils art_stringForKey:@"ktongdaoUUIDString"];
        if (nil == _deviceUniqueId) {
            _deviceUniqueId = [[[NSUUID UUID] UUIDString] lowercaseString];
        }
        if ([self isNotBlank:_deviceUniqueId]) {
            [YBKeychainUtils art_saveString:_deviceUniqueId forKey:@"ktongdaoUUIDString"];
        };
    }
    return _deviceUniqueId;
}

+ (BOOL)isNotBlank:(NSString *)string {
    NSCharacterSet *blank = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    for (NSInteger i = 0; i < string.length; ++i) {
        unichar c = [string characterAtIndex:i];
        if (![blank characterIsMember:c]) {
            return YES;
        }
    }
    return NO;
}

static YBKeychainUtils *_instance;
+ (instancetype)sharedKeyChain {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^ {
        _instance = [[self alloc] init];
        _instance.keyChain = [UICKeyChainStore keyChainStoreWithService:[[NSBundle mainBundle] bundleIdentifier]];
    });

    return _instance;
}

+ (BOOL)art_saveString:(NSString *)str forKey:(NSString *)key {
    NSError *error;
    [_instance.keyChain setString:str forKey:key error:&error];
    if (error) {
        NSLog(@"存储字符串数据到KeyChain中失败，错误信息：【%@】", error.localizedDescription);
        return NO;
    }
    return YES;
}

+ (BOOL)art_saveData:(NSData *)data forKey:(NSString *)key {
    NSError *error;
    [_instance.keyChain setData:data forKey:key error:&error];
    if (error) {
        NSLog(@"存储二进制数据到KeyChain中失败，错误信息：【%@】", error.localizedDescription);
        return NO;
    }
    return YES;
}

+ (NSString *)art_stringForKey:(NSString *)key {
    return [_instance.keyChain stringForKey:key];
}

+ (NSData *)ib_dataForKey:(NSString *)key {
    return [_instance.keyChain dataForKey:key];
}

+ (BOOL)ib_removeItemForKey:(NSString *)key {
    NSError *error;
    [_instance.keyChain removeItemForKey:key error:&error];
    if (error) {
        NSLog(@"删除key为【%@】对应值失败，错误信息：【%@】", key, error.localizedDescription);
        return NO;
    }
    return YES;
}

+ (void)et_removeAllItem {
    [UICKeyChainStore removeAllItems];
}

+ (void)et_removeAllItemsForService:(NSString *)service {
    [UICKeyChainStore removeAllItemsForService:service];
}

@end
